<template>
   <el-card class="box-card" shadow="never">
    <div slot="header" class="clearfix">
      <h3>重置密码</h3>
    </div>
    <el-form :model="ruleForm"  :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="原密码" prop="old_pwd" >
        <el-input v-model="ruleForm.old_pwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input type="new_pwdword" v-model="ruleForm.new_pwd" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input type="new_pwdword" v-model="ruleForm.re_pwd" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">修改密码</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

  </el-card>
</template>

<script>
import { patchuserpassword } from '@/api/user'
export default {
  name: 'BigEventIndex',

  data () {
    // const checkold_pwd = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('旧密码不能为空'))
    //   } else if (value !== this.old_pass) {
    //     callback(new Error('请输入正确旧密码!'))
    //   } else {
    //     callback()
    //   }
    // }
    const validatenew_pwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.re_pwd !== '') {
          this.$refs.ruleForm.validateField('re_pwd')
        }
        callback()
      }
    }
    const validatenew_pwd2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.new_pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        new_pwd: '',
        re_pwd: '',
        old_pwd: ''
      },
      rules: {
        new_pwd: [
          { validator: validatenew_pwd, required: true, trigger: 'blur' }
        ],
        re_pwd: [
          { validator: validatenew_pwd2, required: true, trigger: 'blur' }
        ],
        old_pwd: [
          { min: 6, max: 15, message: '请输入6-15位密码', required: true, trigger: 'blur' }
        ]
      }
    }
  },

  mounted () {
  },

  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async update () {
      await this.$refs.ruleForm.validate()
      const { data } = await patchuserpassword(this.ruleForm)
      if (data.code === 0) {
        this.$message.success(data.message)
      } else {
        this.$message.warning(data.message)
      }
      this.reset()
    },
    reset () {
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 25rem;
}

</style>
